<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { merge } from 'lodash-es'
import { useRoute } from 'vue-router'
import { optimizationConfig } from '../../config'
import type { ICaseTableItem } from '../../type'
import { runCase, updateCase } from '@/api/cases'
import { scatterBaseOptions } from '@/components/ui/chart/src/scatterOptions'
import useStore from '@/stores'
import { useFetch } from '@/composables/useFetch'
import { isEmptyObject } from '@/utils'
import { useCaseResult } from '@/views/cases/components/useCaseResult'

const route = useRoute()
const { cases } = useStore()
const caseInfo = computed(() => cases.caseInfo)
const detailData = computed(() => caseInfo.value?.jsonArgs ? JSON.parse(caseInfo.value?.jsonArgs) : null)
const optimizationFormRef = ref()
const tableData = ref([])
const scatterOptions = ref(scatterBaseOptions)

const { loading: runLoading, execute: runCaseExecute } = useFetch((parmas: any = {}) => runCase(parmas))
const { execute: updateCaseExecute } = useFetch((parmas: ICaseTableItem) => updateCase(parmas))

// 获取结果
const { optimizationResult, optimizationLoading, onClickRefreshAllAction } = useCaseResult()
watch(() => optimizationResult.value, () => {
  if (isEmptyObject(optimizationResult.value)) {
    tableData.value = []
    scatterOptions.value = scatterBaseOptions
    return
  }

  _handleCaseResultData(optimizationResult.value)
}, { deep: true })

// 共用一个按钮加载状态
watch(() => runLoading.value, (val: boolean) => {
  cases.setCaseRunLoading(val)
})

// 保存表单信息
watch([() => optimizationFormRef.value?.model], () => {
  cases.initFormInfoSkip()
  const formInfo = Object.assign({}, cases.formInfo, { Optimization: { ...optimizationFormRef.value.model, skip: false } })
  cases.saveFormInfo(formInfo)
}, { deep: true })

// 接口的表单字段有变化需要重新回填表单
watch(() => detailData.value?.Optimization, (nVal: any) => {
  if (nVal)
    initForm()
}, { deep: true })

onMounted(() => {
  initForm()
})

onBeforeUnmount(() => {
  optimizationResult.value = null as any
  tableData.value = scatterOptions.value = null as any
})

function initForm() {
  if (detailData.value && !isEmptyObject(detailData.value))
    optimizationFormRef.value.model = detailData.value.Optimization
}

function onClickSubmitRun() {
  const validate = optimizationFormRef.value.validate()
  validate().then(async () => {
    // 后端进行缓存全量参数
    await updateCaseExecute({ caseId: route.query.id, jsonArgs: JSON.stringify(cases.formInfo) })

    // 运行操作
    await runCaseExecute({ caseId: route.query.id })
  })
}

function _handleCaseResultData(resultData: any) {
  const { opt_2d, opt_table } = resultData
  _handleTableData(opt_table)
  _setChartOption(opt_2d)
}

function _handleTableData(rawTable: any) {
  tableData.value = rawTable['dataset-records'].map((item: any, index: number) => {
    item.dbi_score = (+item.dbi_score).toFixed(3)
    item.sil_score = (+item.sil_score).toFixed(3)
    return { index: index + 1, ...item }
  })
}

function _setChartOption(data: any) {
  scatterOptions.value = merge(
    {},
    scatterBaseOptions,
    {
      xAxis: { name: 'sil_score' },
      yAxis: { name: 'dbi_score' },
      legend: {
        data: data.serie_names,
      },
      series: data.series.map((item: any) => {
        return {
          name: item.name,
          data: item.data,
          type: 'scatter',
          symbolSize: '5',
        }
      }),
    },
  )
}

defineExpose({ onClickSubmitRun, onClickRefreshAllAction })
</script>

<template>
  <div class="case-optimization-wrapper case-form-wrapper">
    <GpForm ref="optimizationFormRef" layout="vertical" :options="optimizationConfig.optimizationFormOptions" class="gp__grid-three" />
    <div class="raw-box">
      <div class="header">
        <span class="name">Optimization Table</span>
      </div>
      <div class="content" style="padding: 10px">
        <a-table :columns="optimizationConfig.optimizationColumns" :loading="optimizationLoading" :data-source="tableData" :scroll="{ x: 1080 }" size="middle" />
      </div>
    </div>
    <div class="chart-box">
      <a-card title="Optimization 2d">
        <a-spin tip="loading..." :spinning="optimizationLoading">
          <GpChart id="caseOptimizeScatter" style="margin: 0 auto;" width="50%" height="400px" :options="scatterOptions" />
        </a-spin>
      </a-card>
    </div>
  </div>
</template>

<style lang="less" scoped>
@import url('../../common.less');
.case-optimization-wrapper {
  .raw-box {
    width: 100%;
    background-color: #fff;
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    margin-bottom: 20px;
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      min-height: 56px;
      margin-bottom: -1px;
      padding: 0 24px;
      color: rgba(0, 0, 0, 0.88);
      font-weight: 600;
      font-size: 16px;
      border-bottom: 2px solid #f0f0f0;
      border-radius: 8px 8px 0 0;
      font-family: 'Web_SemiBold';
      background: @color-page-header;
    }
  }
}
</style>
